import PermissionDao from '../dao/PermissionDao.js'
import RoleDao from '../dao/RoleDao.js'

//查询所有权限
let permissions = await PermissionDao.selectByLimit(0, 999)
//遍历所有权限并把method转为大写，去除权限路径前面和后面的/
permissions.forEach(permission => {
    permission.method = permission.method.toUpperCase()

    if (permission.name.startsWith('/')) {
        permission.name = permission.name.slice(1)
    }

    if (permission.name.endsWith('/')) {
        permission.name = permission.name.slice(0, -1)
    }
})

//查收获取访客角色guest 并作为访客默认权限
let guest_role = await RoleDao.selectByName('guest')
let guest_permission = []

if (guest_role instanceof Error) {
    console.log('guest角色未设置')
} else {
    //如果已设置访客角色 就遍历获取访客所有权限
    for (const permission_id of guest_role.permission_ids) {
        guest_permission.push( permissions.find(permission => permission.id === permission_id) )
    }
}

export default (req, res, next) => {
    //获取当前请求user，method，path
    let user = req.session.user
    let method = req.method.toUpperCase()
    let path = req.path

    //去除path开头结尾的/
    if (path.startsWith('/')) {
        path = path.slice(1)
    }
    if (path.endsWith('/')) {
        path = path.slice(0, -1)
    }

    //根据当前path，method 遍历所有权限，匹配失败就返回404
    let result = permissions.find(permission => {
        if ( method !== 'GET' ) {
            return permission.name === path && permission.method === method
        } else {
            return path.startsWith(permission.name) && permission.method === method
        }
    })

    if (!result) return res.end(JSON.stringify({ code: 404, msg: '请求路径不存在' }))

    if (user) {

        //如果登录用户为zx跳过所有权限验证
        if (user.username === 'zx') return next()

        if (!user.permissions) {
            user.permissions = []

            for (let i = 0; i < user.permission_ids.length; i++) {
                user.permissions.push( permissions.find(permission => permission.id === user.permission_ids[i]) )
            }
        }

        //如果用户已登陆 根据当前path，method 遍历user权限，匹配失败就返回403
        let result = user.permissions.find(permission => {
            if ( method !== 'GET' ) {
                return permission.name === path && permission.method === method
            } else {
                return path.startsWith(permission.name) && permission.method === method
            }
        })

        if (!result) return res.end(JSON.stringify({ code: 403, msg: '没有权限!!!' }))
    } else {
        //如果当前是访客 根据当前path，method 遍历guest权限，匹配失败就返回403
        let result = guest_permission.find(permission => {
            if ( method !== 'GET' ) {
                return permission.name === path && permission.method === method
            } else {
                return path.startsWith(permission.name) && permission.method === method
            }
        })
        
        if (!result) return res.end(JSON.stringify({ code: 403, msg: '没有权限!!!' }))
    }

    next()
}